package test.enba.excel.controller;

import com.enba.boot.excel.ExcelService;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import test.enba.excel.test.Person;

@RestController
@RequestMapping("/excel")
public class ExcelController {

  @Autowired private ExcelService excelService;

  /** 根据集合数据生成excel下载 */
  @GetMapping("/download")
  public void download(HttpServletResponse response) throws IOException {
    // 设置响应头信息
    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("utf-8");
    // 这里URLEncoder.encode可以防止中文乱码
    String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    List<Person> peopleList = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
      Person person = new Person();
      person.setId("1");
      person.setName("name" + i);
      person.setAge(i);
      peopleList.add(person);
    }
    excelService.write(response.getOutputStream(), Person.class, peopleList);
  }

  /** 上传解析excel生成集合数据 */
  @PostMapping("/upload")
  public void upload(@RequestParam("file") MultipartFile file, HttpServletRequest request)
      throws IOException {
    List objects = excelService.read(file.getInputStream(), Person.class);
    System.out.println(objects);
  }
}
